package com.cold.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.cold.eduservice.entity.EduSubject;
import com.cold.eduservice.entity.excel.SubjectData;
import com.cold.eduservice.entity.subject.MySubject;
import com.cold.eduservice.listener.SubjectExcelListener;
import com.cold.eduservice.mapper.EduSubjectMapper;
import com.cold.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author cold
 * @since 2021-01-27
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try{
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    @Override
    public List<MySubject> getAllSubject() {
        List<EduSubject> allSubject = list(null);
        List<MySubject> mySubjects = new ArrayList<>();
        for(EduSubject eduSubject :allSubject){
            if("0".equals(eduSubject.getParentId() )){
                MySubject mySubject = new MySubject(eduSubject.getId(),eduSubject.getTitle(),new ArrayList<>());
                mySubjects.add(mySubject);
            }else {
                String parentId = eduSubject.getParentId();
                for (MySubject mySubject : mySubjects){
                    String id = mySubject.getId();
                    if(id.equals(parentId)){
                        List<MySubject> children = mySubject.getChildren();
                        MySubject mySubject1 = new MySubject(eduSubject.getId(),eduSubject.getTitle(),null);
                        children.add(mySubject1);
                        break;
                    }
                }
            }
        }
        return mySubjects;
    }
}
